package com.hongkzh.www.mediaShop.service;

import com.google.common.collect.Lists;
import com.hongkzh.www.adv.service.BaseService;
import com.hongkzh.www.conmon.*;
import com.hongkzh.www.user.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.*;

public class MediaShopService extends BaseService {
    @Before(Tx.class)
    public void saveProduct(List<String> imgs, String loginUid, String mediaCategoryId, String userFreightId, String title,
                            String content, String[] model, String[] price, Integer[] num, String isNew) {
        String id = IdGen.uuid();
        int count = 0;
        for (int n : num
        ) {
            count += n;
        }
        Kv cond = Kv.by("uid", loginUid).set("freightId", userFreightId).set("title", title).set("price", price[0]).set("num", count)
                .set("imgSrc", imgs.get(0)).set("id", id).set("isNew", isNew);
        SqlPara sqlPara = Db.getSqlPara("mediaShop.saveProduct", cond);
        Db.update(sqlPara);
        cond = Kv.by("content", content).set("productId", id).set("id", IdGen.uuid());
        sqlPara = Db.getSqlPara("mediaShop.saveProductDetail", cond);
        Db.update(sqlPara);
        cond = Kv.by("categoryId", mediaCategoryId).set("productId", id).set("id", IdGen.uuid());
        sqlPara = Db.getSqlPara("mediaShop.saveProductCategory", cond);
        Db.update(sqlPara);
        for (String s : imgs
        ) {
            cond = Kv.by("imgSrc", s).set("productId", id).set("id", IdGen.uuid());
            sqlPara = Db.getSqlPara("mediaShop.saveProductImg", cond);
            Db.update(sqlPara);
        }

        for (int i = 0; i < model.length; i++
        ) {
            cond = Kv.by("model", model[i]).set("price", price[i]).set("num", num[i]).set("productId", id).set("id", IdGen.uuid());
            sqlPara = Db.getSqlPara("mediaShop.saveProductSku", cond);
            Db.update(sqlPara);
        }

    }

    @Before(Tx.class)
    public void updateProduct(String loginUid, String mediaCategoryId, String userFreightId, String title, String content, String[] model, String[] price, Integer[] num, String[] skuId, String productId) {
        String id = productId;
        int count = 0;
        for (int n : num
        ) {
            count += n;
        }
        Kv cond = Kv.by("uid", loginUid).set("freightId", userFreightId).set("title", title).set("price", price[0]).set("num", count)
                .set("id", productId);
        SqlPara sqlPara = Db.getSqlPara("mediaShop.updateProduct", cond);
        Db.update(sqlPara);
        cond = Kv.by("content", content).set("productId", id).set("id", IdGen.uuid());
        sqlPara = Db.getSqlPara("mediaShop.updateProductDetail", cond);
        Db.update(sqlPara);
        cond = Kv.by("categoryId", mediaCategoryId).set("productId", id).set("id", IdGen.uuid());
        sqlPara = Db.getSqlPara("mediaShop.updateProductCategory", cond);
        Db.update(sqlPara);

        for (int i = 0; i < model.length; i++
        ) {
            if (StrKit.notBlank(skuId[i])) {
                cond = Kv.by("model", model[i]).set("skuId", skuId[i]).set("price", price[i]).set("num", num[i]).set("productId", id);
                sqlPara = Db.getSqlPara("mediaShop.updateProductSku", cond);
                Db.update(sqlPara);
            } else {
                cond = Kv.by("model", model[i]).set("price", price[i]).set("num", num[i]).set("productId", id).set("id", IdGen.uuid());
                sqlPara = Db.getSqlPara("mediaShop.saveProductSku", cond);
                Db.update(sqlPara);
            }
        }
    }

    @Before(Tx.class)
    public void updateProductByImg(List<String> imgs, String loginUid, String mediaCategoryId, String userFreightId, String title, String content, String[] model, String [] price, Integer[] num, String[] skuId, String productId) {
        String id = productId;
        int count = 0;
        for (int n : num
        ) {
            count += n;
        }
        Kv cond = Kv.by("uid", loginUid).set("freightId", userFreightId).set("title", title).set("price", price[0]).set("num", count)
                .set("id", productId);
        SqlPara sqlPara = Db.getSqlPara("mediaShop.updateProduct", cond);
        Db.update(sqlPara);
        cond = Kv.by("content", content).set("productId", id).set("id", IdGen.uuid());
        sqlPara = Db.getSqlPara("mediaShop.updateProductDetail", cond);
        Db.update(sqlPara);
        cond = Kv.by("categoryId", mediaCategoryId).set("productId", id).set("id", IdGen.uuid());
        sqlPara = Db.getSqlPara("mediaShop.updateProductCategory", cond);
        Db.update(sqlPara);
        for (String s : imgs
        ) {
            cond = Kv.by("imgSrc", s).set("productId", id).set("id", IdGen.uuid());
            sqlPara = Db.getSqlPara("mediaShop.saveProductImg", cond);
            Db.update(sqlPara);
        }

        for (int i = 0; i < model.length; i++
        ) {
            if (StrKit.notBlank(skuId[i])) {
                cond = Kv.by("model", model[i]).set("skuId", skuId[i]).set("price", price[i]).set("num", num[i]).set("productId", id);
                sqlPara = Db.getSqlPara("mediaShop.updateProductSku", cond);
                Db.update(sqlPara);
            } else {
                cond = Kv.by("model", model[i]).set("price", price[i]).set("num", num[i]).set("productId", id).set("id", IdGen.uuid());
                sqlPara = Db.getSqlPara("mediaShop.saveProductSku", cond);
                Db.update(sqlPara);
            }

        }
    }

    @Before(Tx.class)
    public List<Record> freightList(String loginUid) {
        List<Record> sublist;
        List<Record> list = Db.find(Db.getSqlPara("mediaShop.freightList", loginUid));
        String id;
        if (null == list || list.size() == 0) {
            list = Db.find(Db.getSqlPara("mediaShop.systemfreightList"));
            for (Record r : list) {
                sublist = Db.find(Db.getSqlPara("mediaShop.systemareafreightList", r.getStr("freightId")));
                id = IdGen.uuid();
                r.set("id", id);
                r.set("uid", loginUid);
                r.set("isSystem", "1");
                Db.update(Db.getSqlPara("mediaShop.savefreight", r));
                for (Record s : sublist
                ) {
                    s.set("id", IdGen.uuid());
                    s.set("freightId", id);
                    s.set("uid", loginUid);
                    Db.update(Db.getSqlPara("mediaShop.saveareafreight", s));
                }
            }
            list = Db.find(Db.getSqlPara("mediaShop.freightList", loginUid));
        }
        StringBuffer sb = new StringBuffer();
        for (Record r : list) {
            sb.setLength(0);
            if (StrKit.notBlank(r.getStr("provinceId"))) {
                for (String s : r.getStr("provinceId").split(",")) {
                    if (StrKit.notBlank(RedisTool.hgetArea(s))) {
                        sb.append(RedisTool.hgetArea(s)).append(",");
                    }
                }
            }
            r.set("provinceName", sb.toString());

            sublist = Db.find(Db.getSqlPara("mediaShop.areafreightList", r.getStr("freightId")));
            for (Record s : sublist
            ) {
                sb.setLength(0);
                if (StrKit.notBlank(s.getStr("provinceId"))) {
                    for (String s2 : s.getStr("provinceId").split(",")) {
                        if (StrKit.notBlank(RedisTool.hgetArea(s2))) {
                            sb.append(RedisTool.hgetArea(s2)).append(",");
                        }
                    }
                }
                s.set("provinceName", sb.toString());
            }

            r.set("sublist", sublist);
        }
        return list;
    }

    @Before(Tx.class)
    public void deletefreight(String loginUid, String freightId) {
        Db.update(Db.getSqlPara("mediaShop.deletefreight", freightId, loginUid));
        Db.update(Db.getSqlPara("mediaShop.deleteareafreightByfreightId", freightId, loginUid));

    }

    @Before(Tx.class)
    public void deleteareafreight(String loginUid, String areafreightId) {
        Db.update(Db.getSqlPara("mediaShop.deleteareafreight", areafreightId, loginUid));
    }

    @Before(Tx.class)
    public void savefreight(String loginUid, String name, String freightId, String isExcept, String provinceId, String piece,
                            String money, String addPiece, String addMoney, String[] areafreightId, String[] subprovinceId,
                            String[] subpiece, String[] submoney, String[] subaddPiece, String[] subaddMoney) {
        if (StrKit.notBlank(freightId)) {
            //修改
            Record record = new Record();
            record.set("id", freightId);

            record.set("isExcept", isExcept);
            record.set("piece", piece);
            record.set("money", money);
            record.set("addPiece", addPiece);
            record.set("addMoney", addMoney);
            record.set("name", name);
            record.set("provinceId", provinceId);
            record.set("uid", loginUid);
            Db.update(Db.getSqlPara("mediaShop.updatefreight", record));
            if (subpiece != null && subpiece.length > 0) {
                for (int i = 0; i < subpiece.length; i++) {
                    if (StrKit.isBlank(subpiece[i])) {
                        return;
                    }
                    Record record2 = new Record();
                    record2.set("freightId", freightId);
                    record2.set("piece", subpiece[i]);
                    record2.set("money", submoney[i]);
                    record2.set("addPiece", subaddPiece[i]);
                    record2.set("addMoney", subaddMoney[i]);
                    record2.set("provinceId", subprovinceId[i]);
                    record2.set("uid", loginUid);
                    if (StrKit.notBlank(areafreightId[i])) {
                        record2.set("id", areafreightId[i]);
                        Db.update(Db.getSqlPara("mediaShop.updateareafreight", record2));

                    } else {
                        record2.set("id", IdGen.uuid());
                        Db.update(Db.getSqlPara("mediaShop.saveareafreight", record2));

                    }
                }

            }
        } else {
            //新增
            freightId = IdGen.uuid();
            Record record = new Record();
            record.set("id", freightId);
            record.set("isSystem", 0);
            record.set("isExcept", isExcept);
            record.set("piece", piece);
            record.set("money", money);
            record.set("addPiece", addPiece);
            record.set("addMoney", addMoney);
            record.set("name", name);
            record.set("provinceId", provinceId);
            record.set("uid", loginUid);
            Db.update(Db.getSqlPara("mediaShop.savefreight", record));
            if (subpiece != null && subpiece.length > 0) {
                for (int i = 0; i < subpiece.length; i++) {
                    if (StrKit.isBlank(subpiece[i])) {
                        return;
                    }
                    Record record2 = new Record();
                    record2.set("id", IdGen.uuid());
                    record2.set("freightId", freightId);
                    record2.set("piece", subpiece[i]);
                    record2.set("money", submoney[i]);
                    record2.set("addPiece", subaddPiece[i]);
                    record2.set("addMoney", subaddMoney[i]);
                    record2.set("provinceId", subprovinceId[i]);
                    record2.set("uid", loginUid);
                    Db.update(Db.getSqlPara("mediaShop.saveareafreight", record2));
                }
            }


        }
    }

    private List<Record> doCart(List<Record> rs) {
        List<Record> records = Lists.newLinkedList();
        Map<String, Record> map = new LinkedHashMap<>();
        /* Map<String, List<Record>> shopmap = new HashMap<>();*/
        String mediaUserId = "";
        String shopId = "";
        List<Record> temList = Lists.newLinkedList();
        Record tempRecord = new Record();
        /*  List<Record> shoptemList = Lists.newArrayList();*/
        Record user;
        String id = "";

        for (Record r : rs) {
            try {
                doCartSku(r);
            } catch (Exception e) {
                continue;
            }
            doImgPath(r);

            mediaUserId = r.getStr("mediaUserId");
            if (StrKit.notBlank(mediaUserId) && !"0".equals(mediaUserId)) {
                id = mediaUserId;
                user = Db.findFirst(Db.getSqlPara("user.getUserHeadImgInfo", mediaUserId));
                r.set("name", user.getStr("name"));
                r.set("headImg", user.getStr("headImg"));
                r.set("shopId", "");
                r.set("mediaUserId", mediaUserId);

            }
            shopId = r.getStr("shopId");
            if (StrKit.notBlank(shopId)) {
                id = shopId;
                user = Db.findFirst(Db.getSqlPara("shop.getShopById", shopId));
                r.set("name", user.getStr("name"));
                r.set("headImg", user.getStr("imgSrc"));
                r.set("mediaUserId", "");
                r.set("shopId", shopId);
            }
            doImgPath(r);

            if (map.containsKey(id)) {
                tempRecord = map.get(id);
                temList = tempRecord.get("products");
                temList.add(r);
                tempRecord.set("products", temList);
                map.put(id, tempRecord);
            } else {
                temList = new ArrayList<>();
                tempRecord = new Record();
                tempRecord.set("name", r.getStr("name"));
                tempRecord.set("headImg", r.getStr("imgSrc"));
                tempRecord.set("shopId", r.getStr("shopId"));
                tempRecord.set("mediaUserId", r.getStr("mediaUserId"));
                temList.add(r);
                tempRecord.set("products", temList);
                map.put(id, tempRecord);

            }
        }
        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            records.add((Record) entry.getValue());

        }
        /* Set<Map.Entry<String, List<Record>>> en = map.entrySet();
         *//*  Set<Map.Entry<String, List<Record>>> shopmapen = shopmap.entrySet();

        for (Map.Entry<String, List<Record>> e : shopmapen) {
            Record r = new Record();
            user = Db.findFirst(Db.getSqlPara("shop.getShopById", e.getKey()));
            r.set("name", user.getStr("name"));
            r.set("headImg", user.getStr("imgSrc"));
            doImgPath(r);
            r.set("mediaUserId", "");
            r.set("shopId", e.getKey());
            r.set("products", e.getValue());
            records.add(r);
        }*//*

        for (Map.Entry<String, List<Record>> e : en) {
            Record r = new Record();
            doImgPath(r);
            records.add(r);
        }*/

        return records;
    }

    public List<Record> cartList(String loginUid, String type) {
        List<Record> rs = Db.find(Db.getSqlPara("mediaShop.selectCartListEx", loginUid, type));

        return this.doCart(rs);
    }

    /**
     * 购物车
     *
     * @param loginUid
     * @param shopId
     * @param productId
     * @param skuId
     * @param number
     * @param mediaUserId
     */
    @Before(Tx.class)
    public Record addCart(String loginUid, String shopId, String productId, String skuId, String number, String mediaUserId, String type, String isBuyNow) {
        String cartId = "";

        if (StrKit.notBlank(shopId)) {
            Record sku = Db.findFirst(Db.getSqlPara("mediaShop.getSkuinfo", skuId, productId));
            if (sku != null) {
                cartId = sku.getStr("sku_id");
                  /*if(StrKit.notBlank(sku.getStr("activity_type"))){
                       if("1".equals(sku.getStr("activity_type"))||"2".equals(sku.getStr("activity_type")))
                      {
                          sku.set("endtime",DateUtil.addHour(1));
                    }
                   else if("3".equals(sku.getStr("activity_type"))){
                          sku.set("endtime",DateUtil.get22());
                      }
                      Db.update(Db.getSqlPara("mediaShop.deleteCartBySkuId",loginUid,skuId));
                      sku.set("id",IdGen.uuid());
                      sku.set("number",number);
                      sku.set("hk_user_id","");
                      sku.set("shop_id",shopId);
                      sku.set("user_id",loginUid);
                      Db.update(Db.getSqlPara("mediaShop.addCart",sku));
                  }
                  else{*/
                Record cart = Db.findFirst(Db.getSqlPara("mediaShop.selectCartBuskuId", loginUid, skuId, productId));
                if (cart != null) {
                    cartId = cart.get("id");
                    if (isBuyNow.equals("0") && StrKit.isBlank(mediaUserId)) {
                        Db.update(Db.getSqlPara("mediaShop.updateCartByNow", loginUid, skuId, number, productId));
                    } else {
                        Db.update(Db.getSqlPara("mediaShop.updateCart", loginUid, skuId, number, productId));
                    }
                } else {
                    cartId = IdGen.uuid();
                    sku.set("id", cartId);
                    sku.set("number", number);
                    sku.set("hk_user_id", "");
                    sku.set("user_id", loginUid);
                    sku.set("shop_id", shopId);
                    sku.set("type", type);
                    Db.update(Db.getSqlPara("mediaShop.addCart", sku));
                }

                /*   }*/

            }

        } else {
            if (StrKit.notBlank(mediaUserId)) {
                Record sku = Db.findFirst(Db.getSqlPara("mediaShop.getUserSkuinfo", skuId, productId));

                if (sku != null) {
                    cartId = sku.getStr("sku_id");
                    Record cart = Db.findFirst(Db.getSqlPara("mediaShop.selectCartBuskuId", loginUid, skuId, productId));
                    if (cart != null) {
                        cartId = cart.get("id");
                        if (isBuyNow.equals("0") && StrKit.isBlank(mediaUserId)) {
                            Db.update(Db.getSqlPara("mediaShop.updateCartByNow", loginUid, skuId, number, productId));
                        } else {
                            Db.update(Db.getSqlPara("mediaShop.updateCart", loginUid, skuId, number, productId));
                        }
                    } else {
                        cartId = IdGen.uuid();
                        sku.set("id", cartId);
                        sku.set("number", number);
                        sku.set("hk_user_id", sku.getStr("userId"));
                        sku.set("user_id", loginUid);
                        sku.set("shop_id", "");
                        sku.set("type", type);
                        Db.update(Db.getSqlPara("mediaShop.addCart", sku));
                    }


                }
            }

        }
        return new Record().set("cartCount", this.cartCount(loginUid, type)).set("cartId", cartId);
    }


    private void deleteCart(String loginUid, String[] cartIds) {
        for (String str : cartIds) {

            Db.update(Db.getSqlPara("mediaShop.deleteCartByid", loginUid, str));

        }
    }

    public Record preorder(String loginUid, String[] cartIds, String addressId, String[] skuProductCouponId) {
        //产品折扣券
        Map<String, String> map1 = new HashMap();
        //sku折扣券
        Map<String, String> map4 = new HashMap();
        //已用产品折扣券
        Map<String, String> map2 = new HashMap();
        //是否抵扣
        Map<String, String> map3 = new HashMap();
        if (null != skuProductCouponId && skuProductCouponId.length > 0) {
            for (String s : skuProductCouponId
            ) {
                String a[] = s.split("-");
                if (StrKit.notBlank(a[2])) {
                    map4.put(a[0], a[2]);
                    map1.put(a[1], a[2]);
                }
                if (StrKit.notBlank(a[3])) {
                    map3.put(a[0], a[3]);
                } else {
                    map3.put(a[0], "0");
                }
            }
        }
        Record r = new Record();
        r.set("userIntegral", 0);
        SqlPara sqlPara;
        Record address;
        if (StrKit.notBlank(addressId)) {
            sqlPara = Db.getSqlPara("user.getUserDefalutDeliveryAddressById", addressId);
            address = Db.findFirst(sqlPara);
        } else {
            sqlPara = Db.getSqlPara("user.getUserDefalutDeliveryAddressByUserId", loginUid);
            address = Db.findFirst(sqlPara);
        }

        String provinceId = null;

        int freightIntegral = 0;
        r.set("address", null);

        if (address != null) {
            r.set("address", address);
            provinceId = address.getStr("provinceId");
        }

        int userIntegral = 0;
        Record userIntegralRecord = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
        if (userIntegralRecord != null) {
            userIntegral = userIntegralRecord.getInt("integral");
        }

        r.set("userIntegral", userIntegral);
        List<Record> list = Lists.newArrayList();
        double productIntegral = 0;
        Record cart;
        double dk = 0;
        double alldk = 0;
        double cproductIntegral = 0;
        DecimalFormat df = new DecimalFormat("#0.00");
        DecimalFormat df2 = new DecimalFormat("#0");
        for (String str : cartIds) {
            dk = 0;
            cart = Db.findFirst(Db.getSqlPara("mediaShop.selectCartById", loginUid, str));
            doCartSku(cart);
            cart.set("couponId", "");
            int num = cart.getInt("number");
            String productId = cart.getStr("productId");

            if (StrKit.notBlank(cart.getStr("mediaUserId"))) {
                String skuIdStr = cart.getStr("skuId");
                Record pnum = Db.findFirst(Db.getSqlPara("mediaShop.selectUserProductSkuById", skuIdStr, num));
                if (pnum == null) {
                    throw new BusinessException("网络异常！");
                }
            }

            if (StrKit.notBlank(cart.getStr("shopId"))) {
                Record pnum = Db.findFirst(Db.getSqlPara("mediaShop.selectShopProductSkuById", cart.getStr("skuId"), num));
                if (pnum == null) {
                    throw new BusinessException("网络异常！");
                }
            }


            if (null != map1.get(productId) && null == map2.get(productId) && null != map4.get(cart.getStr("skuId"))) {
                cproductIntegral = 0;
                String couponId = map1.get(productId);
                map2.put(productId, couponId);
                Record cp = Db.findFirst(Db.getSqlPara("shop.getMyCouponsById", loginUid, couponId));
                double discount = 10;
                if (null != cp) {
                    discount = cp.getDouble("discount");
                    cart.set("couponId", couponId);
                }
                cproductIntegral = (cart.getDouble("integral") * discount / 10);
                productIntegral += cproductIntegral;
                productIntegral += cart.getDouble("integral") * (num - 1);
                cproductIntegral += cart.getDouble("integral") * (num - 1);
            } else {
                productIntegral += cart.getDouble("integral") * cart.getInt("number");
                cproductIntegral = cart.getDouble("integral") * cart.getInt("number");
            }

            cart.set("couponCount", 0);
            if (StrKit.notBlank(cart.getStr("shopId"))) {
                cart.set("couponCount", Db.findFirst(Db.getSqlPara("shop.getUserProductCouponCount", cart.getStr("productId"), loginUid)).getInt("count"));
            }

            if ("1".equals(map3.get(cart.getStr("skuId")))) {
            if (userIntegral > 0) {
                dk = userIntegral / 100d;
            }
            if (cproductIntegral >= dk) {
                alldk += dk;
                dk = dk * 100;
                userIntegral -= dk;
            } else {
                dk = cproductIntegral;
                alldk += dk;
                dk = dk * 100;
                userIntegral -= dk;
            }

            String skuIdstr = cart.getStr("skuId");
            String a = map3.get(skuIdstr);

            }
            cart.set("isIntegral", null == map3.get(cart.getStr("skuId")) ? "0" : map3.get(cart.getStr("skuId")));
//            cart.set("isIntegral",0);
            cart.set("offsetCoin", df2.format(dk));
            list.add(cart);
            //自媒体运费
            if (address != null && StrKit.notBlank(cart.getStr("mediaUserId"))) {
                freightIntegral += this.countFreightIntegral(cart, provinceId);
            }
            //店铺运费
            if (address != null && StrKit.notBlank(cart.getStr("shopId"))) {
                freightIntegral += this.countShopFreightIntegral(cart, provinceId);
            }
        }

        r.set("countOffsetCoin", df.format(Double.valueOf(alldk)));
        r.set("freightIntegral", freightIntegral);
        r.set("productIntegral", productIntegral);
        r.set("countegral", df.format(Double.valueOf(productIntegral + freightIntegral - alldk)));

        List<Record> l = this.doCart(list);
        double mediafreightIntegral = 0;
        List<Record> ps;
        for (Record r1 : l
        ) {
            mediafreightIntegral = 0;
            if (StrKit.notBlank(r1.getStr("mediaUserId")) && !"0".equals(r1.getStr("mediaUserId"))) {
                ps = r1.get("products");
                for (Record c : ps) {
                    mediafreightIntegral += this.countFreightIntegral(c, provinceId);
                }
            }
            if (StrKit.notBlank(r1.getStr("shopId"))) {
                ps = r1.get("products");
                for (Record c : ps) {
                    mediafreightIntegral += this.countShopFreightIntegral(c, provinceId);
                }
            }
            r1.set("mediaFreightIntegral", mediafreightIntegral);
        }
        r.set("list", l);
        return r;
    }

    @Before(Tx.class)
    public Record saveOrder(String loginUid, String[] cartIds, String addressId, String[] skuProductCouponId) {
        //产品折扣券
        Map<String, String> map1 = new HashMap();
        //sku折扣券
        Map<String, String> map4 = new HashMap();
        //已用产品折扣券
        Map<String, String> map2 = new HashMap();
        //是否抵扣
        Map<String, String> map3 = new HashMap();
        DecimalFormat df2 = new DecimalFormat("#0");
        if (null != skuProductCouponId && skuProductCouponId.length > 0) {
            for (String s : skuProductCouponId
            ) {
                String a[] = s.split("-");
                if (StrKit.notBlank(a[2])) {
                    map4.put(a[0], a[2]);
                    map1.put(a[1], a[2]);
                }
                if (StrKit.notBlank(a[3])) {
                    map3.put(a[0], a[3]);
                } else {
                    map3.put(a[0], "0");
                }
            }
        }

        Record r = new Record();
        r.set("userIntegral", 0);
        SqlPara sqlPara;
        Record address;
        sqlPara = Db.getSqlPara("user.getUserDefalutDeliveryAddressById", addressId);
        address = Db.findFirst(sqlPara);
        if (address == null) {
            throw new BusinessException("用户地址为空！");
        }

        int freightIntegral = 0;
        r.set("address", address);
        String provinceId = address.getStr("provinceId");
        Record user = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
        double userIntegral = user.getInt("integral") + 0d;
        r.set("userIntegral", userIntegral);
        List<Record> list = Lists.newArrayList();
        double productIntegral = 0;
        Record cart;
        double dk = 0;
        double alldk = 0;
        double cproductIntegral = 0;
        List<String> orders = Lists.newArrayList();

        for (String str : cartIds
        ) {
            dk = 0;
            cart = Db.findFirst(Db.getSqlPara("mediaShop.selectCartById", loginUid, str));
            if (cart == null) {
                throw new BusinessException("购物车已删除或者已下单");
            }
            doCartSku(cart);
            cart.set("couponId", "");
            int num = cart.getInt("number");
            String productId = cart.getStr("productId");

            if (StrKit.notBlank(cart.getStr("mediaUserId"))) {
                Record pnum = Db.findFirst(Db.getSqlPara("mediaShop.selectUserProductSkuById", cart.getStr("skuId"), num));
                if (pnum == null) {
                    throw new BusinessException("网络异常！");
                }
            }

            if (StrKit.notBlank(cart.getStr("shopId"))) {
                Record pnum = Db.findFirst(Db.getSqlPara("mediaShop.selectShopProductSkuById", cart.getStr("skuId"), num));
                if (pnum == null) {
                    throw new BusinessException("网络异常！");
                }
            }

            cart.set("couponId", "");
            if (null != map1.get(productId) && null == map2.get(productId) && null != map4.get(cart.getStr("skuId"))) {
                cproductIntegral = 0;
                String couponId = map1.get(productId);
                map2.put(productId, couponId);
                Record cp = Db.findFirst(Db.getSqlPara("shop.getMyCouponsById", loginUid, couponId));
                double discount = 10;
                if (null != cp) {
                    discount = cp.getDouble("discount");
                    cart.set("discount", cp.getDouble("discount"));
                    cart.set("couponId", couponId);
                    Db.update(Db.getSqlPara("shop.updateCouponsById", loginUid, couponId));
                }

                cproductIntegral = (cart.getDouble("integral") * discount / 10);
                productIntegral += cproductIntegral;
                productIntegral += cart.getDouble("integral") * (num - 1);
                cproductIntegral += cart.getDouble("integral") * (num - 1);
            } else {
                productIntegral += cart.getDouble("integral") * cart.getInt("number");
                cproductIntegral = cart.getDouble("integral") * cart.getInt("number");
            }

            cart.set("productIntegral", productIntegral);
            cart.set("couponCount", 0);
            if (StrKit.notBlank(cart.getStr("shopId"))) {
                cart.set("couponCount", Db.findFirst(Db.getSqlPara("shop.getUserProductCouponCount", cart.getStr("productId"), loginUid)).getInt("count"));
            }
//            if ("1".equals(map3.get(cart.getStr("skuId")))) {
            if (userIntegral > 0) {
                dk = userIntegral / 100d;
            }
            if (cproductIntegral >= dk) {
                alldk += dk;
                dk = dk * 100;
                userIntegral -= dk;
            } else {
                dk = cproductIntegral;
                alldk += dk;
                dk = dk * 100;
                userIntegral -= dk;
            }
//            }

            cart.set("offsetCoin", df2.format(dk));


            //自媒体运费
            if (address != null && StrKit.notBlank(cart.getStr("mediaUserId"))) {
                freightIntegral += this.countFreightIntegral(cart, provinceId);
            }
            //店铺运费
            if (address != null && StrKit.notBlank(cart.getStr("shopId"))) {
                freightIntegral += this.countShopFreightIntegral(cart, provinceId);
            }
            cart.set("freightIntegral", freightIntegral);
            list.add(cart);
        }


        List<Record> cartList = this.doCart(list);
        for (Record r2 : cartList
        ) {
            doMediaOrder(r2, loginUid, orders, address);
        }
        int qbdk = (int) (alldk * 100);
        DecimalFormat df = new DecimalFormat("#0.00");
        deleteCart(loginUid, cartIds);
        Record ret = new Record();
        ret.set("ordersId", StringUtils.join(orders, ","));
        ret.set("countOffMoney", alldk);
        ret.set("countOffsetCoin", qbdk);
        UserService userService = Enhancer.enhance(UserService.class);
        userService.reduceIntegral(loginUid, qbdk, "订单");
        ret.set("freightIntegral", freightIntegral);
        ret.set("productIntegral", productIntegral);
        ret.set("allIntegral", df.format(Double.valueOf(productIntegral + freightIntegral - alldk)));
        ret.set("user", this.userinfo(loginUid));
        return ret;
    }

    private int doSelfOrder(List<Record> products, String loginUid, List<String> orders, Record address) {
        //乐购拆单
        int allIntegral = 0;
        int freightIntegral = 0;
        int productIntegral = 0;
        Kv cond = Kv.by("user_id", loginUid);
        String orderId = IdGen.uuid();
        String orderNumber = IdGen.getOrderIdByUUId();
        orders.add(orderNumber);
        String limitTime = DateUtil.addHour(12);
        for (Record product : products
        ) {
            productIntegral += product.getInt("integral") * product.getInt("number");
            allIntegral += productIntegral;
            Kv cond2 = Kv.by("id", IdGen.uuid());
            cond2.set("user_id", loginUid);
            cond2.set("shop_id", "");
            cond2.set("hk_user_id", "0");
            cond2.set("orderNumber", orderNumber);
            cond2.set("product_id", product.get("productId"));
            cond2.set("sku_id", product.get("skuId"));
            cond2.set("img_src", product.get("imgSrc"));
            cond2.set("title", product.get("title"));
            cond2.set("integral", product.get("integral"));
            cond2.set("activity_type", null);
            cond2.set("activity_price", null);
            cond2.set("state", "1");
            cond2.set("limitTime", limitTime);
            cond2.set("number", product.get("number"));
            cond2.set("colorName", product.get("colorName"));
            cond2.set("specName", product.get("specName"));

            cond2.set("isStorage", product.get("isStorage"));
            Db.update(Db.getSqlPara("mediaShop.saveOrderDetail", cond2));
        }
        cond.set("hk_user_id", "0");
        cond.set("product_integral", productIntegral);
        cond.set("freight_integral", freightIntegral);
        cond.set("integral", productIntegral);
        cond.set("id", orderId);
        cond.set("orderNumber", orderNumber);
        cond.set("addressId", address.getStr("addressId"));
        cond.set("address", address.getStr("address"));
        cond.set("consignee", address.getStr("consignee"));
        cond.set("phone", address.getStr("phone"));
        cond.set("province_id", address.getStr("provinceId"));
        cond.set("city_id", address.getStr("cityId"));
        cond.set("area_id", address.getStr("areaId"));
        cond.set("shop_id", "");
        cond.set("state", "1");
        cond.set("limitTime", limitTime);
        Db.update(Db.getSqlPara("mediaShop.saveOrder", cond));
        return allIntegral;
    }

    private int doIsStorageOrder(String loginUid, List<String> orders, Record address, Record product) {
        String limitTime = DateUtil.addHour(12);
        Kv cond = Kv.by("user_id", loginUid);
        String orderId = IdGen.uuid();
        String orderNumber = IdGen.getOrderIdByUUId();
        orders.add(orderNumber);
        int productIntegral = product.getInt("integral") * product.getInt("number");
        cond.set("hk_user_id", "0");
        cond.set("product_integral", productIntegral);
        cond.set("freight_integral", 0);
        cond.set("integral", productIntegral);
        cond.set("id", orderId);
        cond.set("orderNumber", orderNumber);
        cond.set("addressId", address.getStr("addressId"));
        cond.set("address", address.getStr("address"));
        cond.set("consignee", address.getStr("consignee"));
        cond.set("phone", address.getStr("phone"));
        cond.set("province_id", address.getStr("provinceId"));
        cond.set("city_id", address.getStr("cityId"));
        cond.set("area_id", address.getStr("areaId"));

        cond.set("state", "1");
        cond.set("limitTime", limitTime);
        Db.update(Db.getSqlPara("mediaShop.saveOrder", cond));

        Kv cond2 = Kv.by("id", IdGen.uuid());
        cond2.set("user_id", loginUid);
        cond2.set("hk_user_id", "0");
        cond2.set("orderNumber", orderNumber);
        cond2.set("product_id", product.get("productId"));
        cond2.set("sku_id", product.get("skuId"));
        cond2.set("img_src", product.get("imgSrc"));
        cond2.set("title", product.get("title"));
        cond2.set("integral", product.get("integral"));
        cond2.set("activity_type", null);
        cond2.set("activity_price", null);
        cond2.set("state", "1");
        cond2.set("limitTime", limitTime);
        cond2.set("number", product.get("number"));
        cond2.set("colorName", product.get("colorName"));
        cond2.set("specName", product.get("specName"));

        cond2.set("isStorage", product.get("isStorage"));
        Db.update(Db.getSqlPara("mediaShop.saveOrderDetail", cond2));
        return productIntegral;

    }

    private int doActityOrder(String loginUid, List<String> orders, Record address, Record product) {

        Kv cond = Kv.by("user_id", loginUid);
        String orderId = IdGen.uuid();
        String orderNumber = IdGen.getOrderIdByUUId();
        orders.add(orderNumber);
        int productIntegral = product.getInt("activityPrice") * product.getInt("number");

        cond.set("hk_user_id", "0");
        cond.set("product_integral", productIntegral);
        cond.set("freight_integral", 0);
        cond.set("integral", productIntegral);
        cond.set("id", orderId);
        cond.set("orderNumber", orderNumber);
        cond.set("addressId", address.getStr("addressId"));

        cond.set("address", address.getStr("address"));
        cond.set("consignee", address.getStr("consignee"));
        cond.set("phone", address.getStr("phone"));
        cond.set("province_id", address.getStr("provinceId"));
        cond.set("city_id", address.getStr("cityId"));
        cond.set("area_id", address.getStr("areaId"));

        cond.set("state", "1");
        cond.set("limitTime", product.getStr("limitTime"));
        Db.update(Db.getSqlPara("mediaShop.saveOrder", cond));
        Kv cond2 = Kv.by("id", IdGen.uuid());
        cond2.set("user_id", loginUid);
        cond2.set("hk_user_id", "0");
        cond2.set("orderNumber", orderNumber);
        cond2.set("product_id", product.get("productId"));
        cond2.set("sku_id", product.get("skuId"));
        cond2.set("img_src", product.get("imgSrc"));
        cond2.set("title", product.get("title"));
        cond2.set("integral", product.getInt("activityPrice"));
        cond2.set("activity_type", product.getStr("activityType"));
        cond2.set("activity_price", product.getInt("activityPrice"));
        cond2.set("state", "1");
        cond2.set("limitTime", product.getStr("limitTime"));
        cond2.set("number", product.get("number"));
        cond2.set("colorName", product.get("colorName"));
        cond2.set("specName", product.get("specName"));
        cond2.set("isStorage", product.get("isStorage"));
        Db.update(Db.getSqlPara("mediaShop.saveOrderDetail", cond2));
        return productIntegral;
    }

    private void doMediaOrder(Record r, String loginUid, List<String> orders, Record address) {
        double allIntegral = 0;
        //按商家拆单
        List<Record> products = r.get("products");
        String couponId = r.getStr("couponId");
        double freightIntegral = 0;
        double productIntegral = 0;
        Kv cond = Kv.by("user_id", loginUid);
        String orderId = IdGen.uuid();
        String orderNumber = IdGen.getOrderIdByUUId();
        orders.add(orderNumber);
        String limitTime = DateUtil.addHour(12);
        String state = "1";
        String payType = "3";
        double offsetCoin = 0;
        for (Record product : products
        ) {
            offsetCoin += Double.parseDouble(product.get("offsetCoin"));
            // productIntegral += product.getDouble("productIntegral");
            productIntegral += product.getDouble("integral") * product.getDouble("number");
            freightIntegral += product.getDouble("freightIntegral");
            allIntegral = productIntegral + freightIntegral;
            Kv cond2 = Kv.by("id", IdGen.uuid());
            cond2.set("user_id", loginUid);
            cond2.set("shop_id", r.getStr("shopId"));
            cond2.set("hk_user_id", r.get("mediaUserId"));
            cond2.set("orderNumber", orderNumber);
            cond2.set("product_id", product.get("productId"));
            cond2.set("sku_id", product.get("skuId"));
            cond2.set("img_src", product.get("imgSrc"));
            cond2.set("title", product.get("title"));
            cond2.set("integral", product.get("integral"));
            cond2.set("activity_type", null);
            cond2.set("activity_price", null);
            cond2.set("state", state);
            cond2.set("limitTime", limitTime);
            cond2.set("number", product.get("number"));
            cond2.set("colorName", product.get("colorName"));
            cond2.set("specName", product.get("specName"));

            cond2.set("isStorage", product.get("isStorage"));
            Db.update(Db.getSqlPara("mediaShop.saveOrderDetail", cond2));
        }
        cond.set("hk_user_id", r.get("mediaUserId"));
        cond.set("product_integral", productIntegral);
        cond.set("freight_integral", freightIntegral);
        cond.set("integral", allIntegral);
        cond.set("id", orderId);
        cond.set("orderNumber", orderNumber);
        cond.set("addressId", address.getStr("addressId"));
        cond.set("address", address.getStr("address"));
        cond.set("consignee", address.getStr("consignee"));
        cond.set("phone", address.getStr("phone"));
        cond.set("province_id", address.getStr("provinceId"));
        cond.set("city_id", address.getStr("cityId"));
        cond.set("area_id", address.getStr("areaId"));
        cond.set("shop_id", r.getStr("shopId"));
        cond.set("state", state);
        cond.set("couponId", couponId);

        cond.set("payIntegral", offsetCoin);
        double lastMoney = offsetCoin / 100d;
        if (lastMoney == allIntegral) {
            payType = "1";  //乐币
        }
        if (offsetCoin == 0) {
            payType = "2"; //现金
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        cond.set("payMoney", df.format(Double.valueOf(productIntegral + freightIntegral - lastMoney)));
        cond.set("payType", payType);
        cond.set("limitTime", limitTime);
        Db.update(Db.getSqlPara("mediaShop.saveOrder", cond));

    }


    public Page<Record> userOrderList(String loginUid, String type, int pageNumber, String name) {

        SqlPara sqlPara = null;
        Page<Record> records = null;
        if (!"100".equals(type)) {
            StringBuffer sb = new StringBuffer();
            if (StrKit.notBlank(loginUid)) {
                sb.append("and o.user_id='").append(loginUid).append("'");
            }
            if ("1".equals(type) || "7".equals(type) || "8".equals(type)) {
                sb.append(" and o.state='").append(type).append("'");
            } else if ("3".equals(type)) {
                sb.append(" and (o.state='3' ").append(" or  o.state='4' ").append(" or o.state='6 ' )");

            }
            if (StrKit.notBlank(name)) {
                sb.append("and d.title like concat(  '%','").append(name).append("', '%')");
            }

            Kv cond = Kv.by("del", '0').set("order", sb.toString());
            sqlPara = Db.getSqlPara("mediaShop.userOrderList", cond);
            records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
            List<Record> list = records.getList();
            List<Record> subList = Lists.newArrayList();
            Record user;
            for (Record r : list) {

                if (StrKit.notBlank(r.getStr("shopId")) && !"0".equals(r.getStr("shopId"))) {

                    user = Db.findFirst(Db.getSqlPara("shop.getShopById", r.getStr("shopId")));
                    r.set("name", user.getStr("name"));
                    r.set("headImg", imgPath(user.getStr("imgSrc")));
                } else {
                    user = Db.findFirst(Db.getSqlPara("user.getUserHeadImgInfo", r.getStr("mediaUserId")));
                    r.set("name", user.getStr("name"));
                    r.set("headImg", imgPath(user.getStr("headImg")));
                }
                subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
                for (Record s : subList) {
                    doImgPath(s);
                }
                r.set("subList", subList);
            }
        } else {

            StringBuffer sb = new StringBuffer();
            if (StrKit.notBlank(loginUid)) {
                sb.append("and o.user_id='").append(loginUid).append("'");
            }
            if (StrKit.notBlank(name)) {
                sb.append("and d.title like concat(  '%','").append(name).append("', '%')");
            }
            Kv cond = Kv.by("del", '0').set("order", sb.toString());
            sqlPara = Db.getSqlPara("mediaShop.userCollageOrderList", cond);
            records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
            List<Record> list = records.getList();
            List<Record> subList = Lists.newArrayList();
            Record user;
            for (Record r : list) {

                if (StrKit.notBlank(r.getStr("shopId")) && !"0".equals(r.getStr("shopId"))) {

                    user = Db.findFirst(Db.getSqlPara("shop.getShopById", r.getStr("shopId")));
                    r.set("name", user.getStr("name"));
                    r.set("headImg", imgPath(user.getStr("imgSrc")));
                }
                subList = Db.find(Db.getSqlPara("mediaShop.userCollageSubOrderList", r.getStr("orderNumber"), loginUid));
                for (Record s : subList) {
                    doImgPath(s);
                }
                r.set("subList", subList);
            }
        }

        return records;
    }

    /**
     * 获取商品现在的价格和库存
     *
     * @param cart 购物车对象
     */
    private void doCartSku(Record cart) {
        if (StrKit.notBlank(cart.getStr("shopId"))) {
            Record sku = Db.findFirst(Db.getSqlPara("mediaShop.getSkuinfo", cart.getStr("skuId"), cart.getStr("productId")));
            if (sku == null) {
                throw new BusinessException("网络异常！");
            }
           /*if(StrKit.notBlank(sku.getStr("activity_type"))){
               cart.set("integral",sku.getInt("activity_price"));
               cart.set("activityPrice",sku.getInt("activity_price"));
               cart.set("activityType",sku.getStr("activity_type"));

           }else {*/
            cart.set("integral", sku.getDouble("integral"));
             /*  cart.set("activityPrice",null);
               cart.set("activityType",null);*/
            /* }*/
            cart.set("productNumber", sku.get("number"));
        } else {
            Record sku = Db.findFirst(Db.getSqlPara("mediaShop.getUserSkuinfo", cart.getStr("skuId"), cart.getStr("productId")));
            cart.set("integral", sku.getDouble("integral"));
          /* cart.set("activityPrice",null);
           cart.set("activityType",null);*/
            cart.set("productNumber", sku.get("number"));
        }
    }


    private int countShopFreightIntegral(Record cart, String provinceId) {
        String productId = cart.getStr("productId");
        int number = cart.getInt("number");
        SqlPara sqlPara = Db.getSqlPara("mediaShop.selectShopProductFreight", productId);
        Record freightId = Db.findFirst(sqlPara);
        if (freightId == null || "0".equals(freightId.getStr("freightId"))) {
            return 0;
        }
        //子运费
        Record aeraFreight = Db.findFirst(Db.getSqlPara("mediaShop.selectAreaFreightByFreightId", freightId.getStr("freightId"), provinceId));
        if (aeraFreight != null) {
            return doNumberPrice(number, aeraFreight);
        } else {
            //主运费
            aeraFreight = Db.findFirst(Db.getSqlPara("mediaShop.selectFreightById", freightId.getStr("freightId")));
            if (aeraFreight == null) {
                return 0;
            }
            if ("0".equals(aeraFreight.getStr("isExcept"))) {
                return doNumberPrice(number, aeraFreight);
            } else {

                if (aeraFreight.getStr("provinceId").contains(provinceId)) {
                    return 0;
                } else {
                    return doNumberPrice(number, aeraFreight);

                }
            }

        }

    }

    private int countFreightIntegral(Record cart, String provinceId) {
        String productId = cart.getStr("productId");
        int number = cart.getInt("number");
        SqlPara sqlPara = Db.getSqlPara("mediaShop.selectProductFreight", productId);
        Record freightId = Db.findFirst(sqlPara);
        if (freightId == null || "0".equals(freightId.getStr("freightId"))) {
            return 0;
        }
        //子运费
        Record aeraFreight = Db.findFirst(Db.getSqlPara("mediaShop.selectAreaFreightByFreightId", freightId.getStr("freightId"), provinceId));
        if (aeraFreight != null) {
            return doNumberPrice(number, aeraFreight);
        } else {
            //主运费
            aeraFreight = Db.findFirst(Db.getSqlPara("mediaShop.selectFreightById", freightId.getStr("freightId")));
            if ("0".equals(aeraFreight.getStr("isExcept"))) {
                return doNumberPrice(number, aeraFreight);
            } else {
                if (aeraFreight.getStr("provinceId").contains(provinceId)) {
                    return 0;
                } else {
                    return doNumberPrice(number, aeraFreight);

                }
            }

        }

    }

    private int doNumberPrice(int num, Record aeraFreight) {
        int piece = aeraFreight.getInt("piece");
        int money = aeraFreight.getInt("money");
        int addPiece = aeraFreight.getInt("addPiece");
        int addMoney = aeraFreight.getInt("addMoney");
        int i = 0;
        if (addPiece == 0) {
            return 0;
        }
        if (num <= piece) {
            i = money;
        } else {
            if (num - piece > 0) {
                double nu = (double) (num - piece) / (double) addPiece;
                if (nu > 1) {
                    if ((double) (num - piece) % (double) addPiece != 0) {
                        nu += 1;
                    }
                } else {
                    nu = 1;
                }
                i = money + ((int) nu * addMoney);
            }
            /*else{
                i = money + (((num - piece) / addPiece) * addMoney);
            }*/
        }

        return i;
    }

    public Integer cartCount(String loginUid, String type) {
        return Db.findFirst(Db.getSqlPara("mediaShop.cartCount", loginUid, type)).getInt("count");
    }

    @Before(Tx.class)
    public Integer deleteCartByid(String loginUid, String cartId, String type) {
        String[] cartids = cartId.split(",");
        for (String c : cartids) {
            Db.update(Db.getSqlPara("mediaShop.deleteCartByid", loginUid, c));
        }
        return this.cartCount(loginUid, type);
    }

    @Before(Tx.class)
    public void updateCart(String loginUid, String cartId, String number) {
        Db.update(Db.getSqlPara("mediaShop.updateCartById", loginUid, cartId, number));
    }

    public Record userOrderInfo(String loginUid, String orderNumber) {
        {


            SqlPara sqlPara = Db.getSqlPara("mediaShop.userOrderInfo", orderNumber);
            Record r = Db.findFirst(sqlPara);
            doPayType(r);
            sqlPara = Db.getSqlPara("user.getUserDefalutDeliveryAddressById", r.getStr("addressId"));
            Record address = Db.findFirst(sqlPara);
            if (null == address) {
                address = new Record();
                address.set("addressId", "");
                address.set("uid", loginUid);
                address.set("isDefault", "1");
            }
            address.set("consignee", r.getStr("consignee"));
            address.set("phone", r.getStr("phone"));
            address.set("address", r.getStr("address"));
            address.set("provinceId", r.getStr("provinceId"));
            address.set("cityId", r.getStr("cityId"));
            address.set("areaId", r.getStr("areaId"));
            r.set("address", address);

            List<Record> subList = Lists.newArrayList();
            Record user;

            if (StrKit.notBlank(r.getStr("mediaUserId")) && !"0".equals(r.getStr("mediaUserId"))) {
                user = Db.findFirst(Db.getSqlPara("user.getUserHeadImgInfo", r.getStr("mediaUserId")));
                r.set("name", user.getStr("name"));
                r.set("headImg", imgPath(user.getStr("headImg")));
            }

            if (StrKit.notBlank(r.getStr("shopId")) && !"0".equals(r.getStr("shopId"))) {
                user = Db.findFirst(Db.getSqlPara("shop.getShopById", r.getStr("shopId")));
                r.set("name", user.getStr("name"));
                r.set("headImg", imgPath(user.getStr("imgSrc")));
            }
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
            List<Record> afterList = Lists.newArrayList();
            afterList = Db.find(Db.getSqlPara("mediaShop.userOrderafterlog", orderNumber));
            r.set("afterList", afterList);
            return r;
        }
    }


    public Record changeAddress(String loginUid, String[] cartIds, String addressId) {
        Record r = new Record();
        SqlPara sqlPara = Db.getSqlPara("user.getUserDefalutDeliveryAddressById", addressId);
        Record address = Db.findFirst(sqlPara);
        int freightIntegral = 0;
        int productIntegral = 0;
        Record cart;
        for (String str : cartIds
        ) {
            cart = Db.findFirst(Db.getSqlPara("mediaShop.selectCartById", loginUid, str));
            doCartSku(cart);
           /* if(StrKit.isBlank(cart.getStr("activityType"))){
                productIntegral+=cart.getInt("integral")*cart.getInt("number");
            }
            else {*/
            productIntegral += cart.getInt("activityPrice") * cart.getInt("number");
            /*     }*/


            if (address != null && !"0".equals(cart.getStr("mediaUserId"))) {
                freightIntegral += this.countFreightIntegral(cart, r.getStr("provinceId"));
            }
        }
        r.set("freightIntegral", freightIntegral);
        r.set("productIntegral", productIntegral);
        r.set("counIntegral", productIntegral + freightIntegral);

        return r;
    }

    @Before(Tx.class)
    public void cartIsStorage(String loginUid, String cartId, String state) {
        Db.update(Db.getSqlPara("mediaShop.updateCartIsStorageById", loginUid, cartId, state));
    }

    /**
     * //订单限制时间
     * //订单金额
     * <p>
     * //用户金额
     * //扣金额
     * 扣库存
     * 修改订单支付时间
     *
     * @param loginUid
     * @param ordersId
     * @return
     */
    @Before(Tx.class)
    public void payOrder(String loginUid, String ordersId) throws BusinessException {

        String[] orders = ordersId.split(",");
        Record order;
        int money = 0;
        List<Record> allOrder = Lists.newArrayList();
        List<Record> allsubsku = Lists.newArrayList();
        List<Record> allsku = Lists.newArrayList();
        Record sku;
        for (String o : orders) {
            order = Db.findFirst(Db.getSqlPara("mediaShop.userOrderInfo", o));
            if (null == order) {
                throw new BusinessException("订单不存在");
            }
            if (!order.getStr("state").equals("1")) {
                throw new BusinessException("订单不是待付款状态");
            }
            allOrder.add(order);
            allsubsku = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", o, loginUid));
            for (Record s : allsubsku) {
                if (StrKit.notBlank(s.getStr("shopId"))) {
                    sku = Db.findFirst(Db.getSqlPara("mediaShop.getSkuinfo", s.getStr("skuId"), s.getStr("productId")));
                    s.set("productNumber", sku.get("number"));
                } else {
                    sku = Db.findFirst(Db.getSqlPara("mediaShop.getUserSkuinfo", s.getStr("skuId"), s.getStr("productId")));
                    s.set("productNumber", sku.get("number"));
                }
                allsku.add(s);
            }

        }
       /* for (Record o:allOrder){
            if(!"1".equals(o.getStr("state"))){
                throw new BusinessException("订单 "+o.getStr("orderNumber")+" 不是待付款状态");
            }

        }*/
        for (Record s : allsku) {
            if (s.getInt("number") > s.getInt("productNumber")) {
                throw new BusinessException("订单 " + s.getStr("orderNumber") + " 库存不够");
            }
        }
        for (Record o : allOrder) {
            if (!DateUtil.compareDate(o.getStr("limitTime"))) {
                throw new BusinessException("订单 " + o.getStr("orderNumber") + "已超时");
            }
            if (o.getStr("payType").equals("1")) {
                Db.update(Db.getSqlPara("mediaShop.updateOrderPayInfo", o.getStr("orderNumber")));
                Db.update(Db.getSqlPara("mediaShop.updateOrderDetailPayInfo", o.getStr("orderNumber")));
            }
            // money+=o.getInt("payIntegral");
        }
        /*Record userIntegralRecord=Db.findFirst(Db.getSqlPara("user.selectUserIntegral",loginUid));
         int userIntegral=userIntegralRecord.getInt("integral");
         if(userIntegral<money){
             throw new BusinessException("用户乐币不够");
         }
         //扣款
         Db.update(Db.getSqlPara("user.reduceIntegral",money,loginUid));
         Db.update(Db.getSql("user.insertUserIntegral"),  IdGen.uuid(), loginUid, money,2, userIntegral - money,"订单");
        */
        //扣库存
        for (Record s : allsku) {
            if (StrKit.notBlank(s.getStr("shopId"))) {
                Db.update(Db.getSqlPara("mediaShop.updateSkuNumber", s.getStr("skuId"), s.getInt("number")));
            } else {
                Db.update(Db.getSqlPara("mediaShop.updateUserSkuNumber", s.getStr("skuId"), s.getInt("number")));
            }
        }


        //是否为纯乐币支付
        for (String o : orders) {
            Record record = Db.findFirst(Db.getSqlPara("mediaShop.selectPayMoneyByOrderNumber", o));
            if (record.getDouble("payMoney") == 0d) {
                Db.update(Db.getSqlPara("mediaShop.updateOrderPayInfo", o));
                Db.update(Db.getSqlPara("mediaShop.updateOrderDetailPayInfo", o));
            }
        }
    }


    /**
     * 充值接口
     *
     * @param loginUid
     * @param ordersId
     * @return
     */
    @Before(Tx.class)
    public void rechargePayOrder(String loginUid, String ordersId) throws BusinessException {


        Record order;
        int money = 0;

        order = Db.findFirst(Db.getSqlPara("mediaShop.userRechargeOrderInfo", ordersId));
        if (null == order) {
            throw new BusinessException("订单不存在");
        }
        if (!order.getStr("state").equals("1")) {
            throw new BusinessException("订单不是待付款状态");
        }


    }


    public Record userinfo(String loginUid) {
        Record user = Db.findFirst(Db.getSqlPara("user.getUserHeadImgInfo", loginUid));
        doImgPath(user);
        return user;
    }

    @Before(Tx.class)
    public void userOrderRefund(String loginUid, String orderNumber, String refundcontact, String refundReason, String refundTelephone, String state, String type) {
        String id = IdGen.uuid();
        Kv cond2 = Kv.by("id", id);
        cond2.set("afterId", id);
        cond2.set("user_id", loginUid);
        cond2.set("orderNumber", orderNumber);
        cond2.set("type", type);
        cond2.set("limitDate", DateUtil.reduceDate(7));
        cond2.set("refundcontact", refundcontact);
        cond2.set("refundReason", refundReason);
        cond2.set("refundTelephone", refundTelephone);
        if (("2").equals(state)) {
            Db.update(Db.getSqlPara("mediaShop.updateuserOrderRefund", cond2));
               /* cond2.set("name","取消退款");
                cond2.set("aftype",2);
                Db.update(Db.getSqlPara("mediaShop.userOrderRefundlog", cond2));*/

        } else {
            if (type.equals("1")) {
                cond2.set("name", "申请退款");
                cond2.set("aftype", 1);
                cond2.set("afterState", "10");
                Db.update(Db.getSqlPara("mediaShop.insertafterlog", cond2));
                Db.update(Db.getSqlPara("mediaShop.userOrderRefund", cond2));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "10"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "10"));
            } else {
                cond2.set("name", "申请退货退款");
                cond2.set("aftype", 1);
                cond2.set("afterState", "60");
                Db.update(Db.getSqlPara("mediaShop.insertafterlog", cond2));
                Db.update(Db.getSqlPara("mediaShop.userOrderRefund", cond2));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "60"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "60"));
            }

        }


    }

    public Page<Record> myUpperProduct(String loginUid, int pageNumber, String state, String order) {
        Record kv = new Record();
        kv.set("uid", loginUid);
        kv.set("isupper", state);
        if (order.equals("1")) {
            kv.set("order2", " order by a.create_date desc ");
        } else if (order.equals("2")) {
            kv.set("order2", " order by a.orderNum desc ");
        } else if (order.equals("3")) {
            kv.set("order2", " order by a.orderNum desc ");
        } else if (order.equals("4")) {
            kv.set("order2", " order by a.num desc ");
        }
        Page<Record> page = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("mediaShop.myUpperProduct", kv));
        for (Record r : page.getList()) {
            doImgPath(r);
            r.set("dayVisitor", 0);
            r.set("daySales", 0);
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
        }
        return page;
    }

    @Before(Tx.class)
    public void upperLowerProduct(String loginUid, String productId, String state) {
        Db.update(Db.getSqlPara("mediaShop.upperLowerProduct", loginUid, productId, state));
    }

    public Page<Record> myAllProduct(String loginUid, int pageNumber, String title) {
        Record kv = new Record();
        kv.set("uid", loginUid);
        kv.set("title", title);
        Page<Record> page = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("mediaShop.myAllProduct", kv));
        for (Record r : page.getList()) {
            doImgPath(r);
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
        }
        return page;
    }

    public Page<Record> sellerorderList(String loginUid, int pageNumber, String title) {

        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("sell.sellOrderList", loginUid, title));
        List<Record> subList;
        for (Record r : records.getList()) {
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return records;
    }

    public Page<Record> sellerorderListByState(String loginUid, int pageNumber, String state) {
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("sell.sellerorderListByState", loginUid, state));
       /* for (Record r:records.getList()){
            doImgPath(r);
            r.set("createDate",DateUtil.FormatDate(r.getDate("createDate")));
        }*/
        List<Record> subList;
        for (Record r : records.getList()) {
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return records;
    }

    public Record sellerorderListHeader(String loginUid) {
        Record record = new Record();
        List<Record> rs = Db.find(Db.getSqlPara("sell.sellerorderListHeader", loginUid));
        int deliveryCount = 0;
        int paymentfCount = 0;
        int shippedCount = 0;
        int salecCount = 0;
        for (Record r : rs
        ) {
            if ("1".equals(r.getStr("state"))) {
                paymentfCount += r.getInt("count");
            }
            if ("3".equals(r.getStr("state"))) {
                deliveryCount += r.getInt("count");
            }
            if ("4".equals(r.getStr("state"))) {
                shippedCount += r.getInt("count");
            }
            if (StrKit.notBlank(r.getStr("afterState")) && (r.getStr("afterState").equals("10") || r.getStr("afterState").equals("40") || r.getStr("afterState").equals("50") || r.getStr("afterState").equals("100"))) {
                salecCount += r.getInt("count");
            }
        }
        record.set("deliveryCount", deliveryCount);
        record.set("paymentfCount", paymentfCount);
        record.set("shippedCount", shippedCount);
        record.set("salecCount", salecCount);

        return record;

    }

    @Before(Tx.class)
    public void sellerupdateorderprice(String loginUid, String orderNumber, int integral, int freightIntegral, int productintegral) {
        Db.update(Db.getSqlPara("sell.sellerupdateorderprice", loginUid, orderNumber, freightIntegral, productintegral, integral));
    }

    @Before(Tx.class)
    public void sellerupdatecloseorder(String loginUid, String orderNumber, String reason) {

        Db.update(Db.getSqlPara("sell.sellerupdatecloseorder", loginUid, orderNumber, reason));

    }

    @Before(Tx.class)
    public void canceluserOrderRefund(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("mediaShop.getAfterIdByOrderNumber", loginUid, orderNumber));
        int i = Db.update(Db.getSqlPara("mediaShop.canceluserOrderRefund", loginUid, orderNumber));
        if (i > 0) {
            record.set("name", "取消退款");
            record.set("aftype", 2);
            record.set("id", IdGen.uuid());
            Db.update(Db.getSqlPara("mediaShop.insertafterlog", record));
            Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "20"));
            Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "20"));
        }
    }


    public Record orderAfterSale(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("mediaShop.orderAfterSale", orderNumber));
        if (record == null) {
            return new Record();
        }
        List<Record> list = Db.find(Db.getSqlPara("mediaShop.orderAfterSaleImgs", record.getStr("afterId")));
        List<String> complaintsImgs = Lists.newArrayList();
        List<String> buyerImgs = Lists.newArrayList();
        List<String> sellerImgs = Lists.newArrayList();
        List<String> refuserefunds = Lists.newArrayList();
        List<String> refuseregoods = Lists.newArrayList();
        for (Record r : list) {
            if ("50".equals(r.get("type"))) {
                complaintsImgs.add(imgPath(r.getStr("imgSrc")));
            }
            if ("100".equals(r.get("type"))) {
                buyerImgs.add(imgPath(r.getStr("imgSrc")));
            }
            if ("110".equals(r.get("type"))) {
                sellerImgs.add(imgPath(r.getStr("imgSrc")));
            }
            if ("40".equals(r.get("type"))) {
                refuserefunds.add(imgPath(r.getStr("imgSrc")));
            }
            if ("80".equals(r.get("type"))) {
                refuseregoods.add(imgPath(r.getStr("imgSrc")));
            }
        }
        record.set("complaintsImgs", complaintsImgs);
        record.set("buyerImgs", buyerImgs);
        record.set("sellerImgs", sellerImgs);
        record.set("refuserefundImgs", refuserefunds);
        record.set("refuseregoodsImgs", refuseregoods);

        return record;
    }

    public Page<Record> myAfterSale(String loginUid, int pageNumber) {

        Page<Record> page = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("mediaShop.myAfterSale", loginUid));
        Record user;
        List<Record> subList;
        for (Record r : page.getList()) {

            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));

            if (StrKit.notBlank(r.getStr("shopId"))) {
                user = Db.findFirst(Db.getSqlPara("shop.getShopById", r.getStr("shopId")));
                r.set("name", user.getStr("name"));
                r.set("headImg", user.getStr("imgSrc"));
            } else {
                user = Db.findFirst(Db.getSqlPara("user.getUserHeadImgInfo", r.getStr("mediaUserId")));
                r.set("name", user.getStr("name"));
                r.set("headImg", user.getStr("headImg"));

            }
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return page;
    }

    @Before(Tx.class)
    public void canceluserOrder(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("mediaShop.userOrderInfo", orderNumber));
        if (record != null) {
            String state = record.getStr("state");
            if ("1".equals(state)) {
                int payIntegral = record.getInt("payIntegral");
                if (payIntegral > 0) {
                    UserService userService = Enhancer.enhance(UserService.class);
                    userService.addIntegral(record.get("userId"), payIntegral, "用户退款");
                }

                Db.update(Db.getSqlPara("mediaShop.updateOrderState", orderNumber, loginUid));
            }
           /* else if("1".equals(state)){

            }*/
        }


    }

    @Before(Tx.class)
    public void deleteuserOrder(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("mediaShop.userOrderInfo", orderNumber));
        if (record != null) {
            String state = record.getStr("state");
            if ("1".equals(state)) {
                int payIntegral = record.getInt("payIntegral");
                if (payIntegral > 0) {
                    UserService userService = Enhancer.enhance(UserService.class);
                    userService.addIntegral(record.get("userId"), payIntegral, "用户退款");
                }
            }
            Db.update(Db.getSqlPara("mediaShop.deleteuserOrder", orderNumber, loginUid));

        }


    }

    @Before(Tx.class)
    public void sellerApprovalOrder(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("10".equals(state) || "66".equals(state)) {
                record.set("name", "同意退款");
                record.set("aftype", 1);
                record.set("id", IdGen.uuid());
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState30", orderNumber, "30"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "30"));
                Db.update(Db.getSqlPara("mediaShop.insertafterlog", record));
                Db.update(Db.getSqlPara("sell.sellerApprovalOrder", orderNumber));
            }
        }
    }

    @Before(Tx.class)
    public void sellerRefuseOrder(String loginUid, String orderNumber, String refundReason, List<String> imgs) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("10".equals(state) || "66".equals(state)) {
                Db.update(Db.getSqlPara("sell.sellerRefuseOrder", orderNumber, refundReason));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState40", orderNumber, "40"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "40"));
                if (null != imgs && imgs.size() > 0) {
                    for (String s : imgs
                    ) {
                        Db.update(Db.getSqlPara("sell.sellerRefuseOrderimgs", IdGen.uuid(), record.getStr("afterId"), s, "40"));
                    }
                }

            }
        }
    }


    public Page<Record> mysellAfterSale(String loginUid, int pageNumber) {

        Page<Record> page = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("sell.mysellAfterSale", loginUid));
        Record user;
        List<Record> subList;
        for (Record r : page.getList()) {
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));

            if (StrKit.notBlank(r.getStr("shopId"))) {

                user = Db.findFirst(Db.getSqlPara("shop.getShopById", r.getStr("shopId")));
                r.set("name", user.getStr("name"));
                r.set("headImg", user.getStr("imgSrc"));
            } else {
                user = Db.findFirst(Db.getSqlPara("user.getUserHeadImgInfo", r.getStr("mediaUserId")));
                r.set("name", user.getStr("name"));
                r.set("headImg", user.getStr("headImg"));


            }
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return page;
    }


    public List<Record> expresList(String loginUid) {
        return Db.find(Db.getSqlPara("mediaShop.expresList"));
    }

    @Before(Tx.class)
    public void sellerOrderDeliver(String loginUid, String orderNumber, String express, String expressNumber) {
        Db.update(Db.getSqlPara("sell.sellerOrderDeliver", loginUid, orderNumber, express, expressNumber));

    }

    @Before(Tx.class)
    public void userOrderComplaint(String loginUid, String orderNumber, String complaintReason, List<String> imgs, String complaintDesc) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("40".equals(state) || "80".equals(state)) {
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "50"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "50"));
                Db.update(Db.getSqlPara("mediaShop.sellerComplaintOrder", orderNumber, complaintReason, complaintDesc));
                if (null != imgs && imgs.size() > 0) {
                    for (String s : imgs
                    ) {
                        Db.update(Db.getSqlPara("sell.sellerRefuseOrderimgs", IdGen.uuid(), record.getStr("afterId"), s, "50"));
                    }
                }

            }
        }
    }

    @Before(Tx.class)
    public void sellerOrderAddress(String loginUid, String orderNumber, String consignee, String phone, String address, String provinceId, String cityId, String areaId) {
        Db.update(Db.getSqlPara("sell.sellerOrderAddress", loginUid, orderNumber, consignee, phone, address, provinceId, cityId, areaId));
    }

    @Before(Tx.class)
    public void agreeReturnGoods(String loginUid, String addressId, String orderNumber) {
        Record address = Db.findFirst(Db.getSqlPara("user.getUserReturnAddressById", addressId));
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("60".equals(state)) {
                record.set("name", "同意退货退款");
                record.set("aftype", 1);
                address.set("orderNumber", orderNumber);
                record.set("id", IdGen.uuid());
                Db.update(Db.getSqlPara("mediaShop.insertafterlog", record));
                Db.update(Db.getSqlPara("sell.selleragreeOrder", address));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState70", orderNumber, "70"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "70"));
            }
        }
    }

    @Before(Tx.class)
    public void canceluserOrderRefundAndGoods(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("mediaShop.getAfterIdByOrderNumber", loginUid, orderNumber));
        int i = Db.update(Db.getSqlPara("mediaShop.canceluserOrderRefundAndGoods", loginUid, orderNumber));
        if (i > 0) {
            record.set("name", "取消退货退款");
            record.set("aftype", 2);
            record.set("id", IdGen.uuid());
            Db.update(Db.getSqlPara("mediaShop.insertafterlog", record));
            Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "65"));
            Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "65"));
        }
    }

    @Before(Tx.class)
    public void refuseReturnGoods(String loginUid, String orderNumber, String refundReason, List<String> imgs) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("60".equals(state)) {
                Db.update(Db.getSqlPara("sell.refuseReturnGoods", orderNumber, refundReason));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState80", orderNumber, "80"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "80"));
                if (null != imgs && imgs.size() > 0) {
                    for (String s : imgs
                    ) {
                        Db.update(Db.getSqlPara("sell.sellerRefuseGoodsOrderimgs", IdGen.uuid(), record.getStr("afterId"), s, "80"));
                    }
                }

            }
        }
    }

    @Before(Tx.class)
    public void returnLogistics(String loginUid, String orderNumber, String courier, String courierNumber) {
        Db.update(Db.getSqlPara("sell.returnLogistics", orderNumber, courier, courierNumber));
    }

    @Before(Tx.class)
    public void sellerProof(String loginUid, String orderNumber, String sellerProof, List<String> imgs, String sellerProofDesc) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("50".equals(state)) {
                Db.update(Db.getSqlPara("sell.sellerProof", orderNumber, sellerProof, sellerProofDesc));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "110"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "110"));
                if (null != imgs && imgs.size() > 0) {
                    for (String s : imgs
                    ) {
                        Db.update(Db.getSqlPara("sell.sellerRefuseGoodsOrderimgs", IdGen.uuid(), record.getStr("afterId"), s, "110"));
                    }
                }

            }
        }
    }

    @Before(Tx.class)
    public void buyerProof(String loginUid, String orderNumber, String buyerProof, List<String> imgs, String buyerProofDesc) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("110".equals(state)) {
                Db.update(Db.getSqlPara("mediaShop.buyerProof", orderNumber, buyerProof, buyerProofDesc));
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "100"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "100"));
                if (null != imgs && imgs.size() > 0) {
                    for (String s : imgs
                    ) {
                        Db.update(Db.getSqlPara("sell.sellerRefuseGoodsOrderimgs", IdGen.uuid(), record.getStr("afterId"), s, "100"));
                    }
                }

            }
        }
    }

    public String logisticsInformation(String courier, String courierNumber) {
        String key = RedisTool.hget("shopexpress:" + courier, "abbreviation");
        String dataKey = key + "-" + courierNumber;
        String str = (String) RedisTool.getObject(dataKey);
        if (StrKit.notBlank(str)) {
            return str;
        }
        str = Kuaidi.getKuaiDiInfo(key, courierNumber);
        RedisTool.setexObject(dataKey, StaticPublic.SHOPEXPRESS, str);
        return str;
    }

    public Record myseller(String loginUid) {
        Record record = Db.findFirst(Db.getSqlPara("sell.dayPayOrder", loginUid));
        record.set("visitors", 0);
        return record;
    }

    @Before(Tx.class)
    public void canceluserOrderComplaint(String loginUid, String orderNumber) {
        Record record = Db.findFirst(Db.getSqlPara("sell.sellerorderafterstate", orderNumber));
        if (record != null) {
            String state = record.getStr("afterState");
            if ("50".equals(state)) {
                Db.update(Db.getSqlPara("mediaShop.updateOrderAfterState", orderNumber, "55"));
                Db.update(Db.getSqlPara("mediaShop.updateAfterOrderAfterState", orderNumber, "55"));
                Db.update(Db.getSqlPara("mediaShop.canceluserOrderComplaint", orderNumber));
            }
        }
    }

    @Before(Tx.class)
    public void confirmCollectGoods(String loginUid, String orderNumber) {
        Db.update(Db.getSqlPara("mediaShop.confirmCollectGoods", loginUid, orderNumber));
    }

    public Page<Record> sellerorderListByTransaction(String loginUid, int pageNumber) {
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("sell.sellerorderListByTransaction", loginUid));

        List<Record> subList;
        for (Record r : records.getList()) {
            r.set("confirmDate", DateUtil.FormatDate(r.getDate("confirmDate")));
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return records;
    }

    public Page<Record> sellerorderListBySettlement(String loginUid, int pageNumber) {
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("sell.sellerorderListBySettlement", loginUid));

        List<Record> subList;
        for (Record r : records.getList()) {
            r.set("confirmDate", DateUtil.FormatDate(r.getDate("confirmDate")));
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return records;
    }

    public Page<Record> sellerorderFlow(String loginUid, int pageNumber, String state) {
        Kv kv = new Kv();
        kv.set("loginUid", loginUid);
        kv.set("state", state);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, Db.getSqlPara("sell.sellerorderFlow", kv));
        List<Record> subList;
        for (Record r : records.getList()) {
            r.set("createDate", DateUtil.FormatDate(r.getDate("createDate")));
            subList = Db.find(Db.getSqlPara("mediaShop.userSubOrderList", r.getStr("orderNumber"), loginUid));
            for (Record s : subList) {
                doImgPath(s);
            }
            r.set("subList", subList);
        }
        return records;
    }

    public Record orderProductCoupon(String loginUid, String productId) {
        Record r = new Record();
        r.set("availableCoupons", Db.find(Db.getSqlPara("shop.orderProductCoupon", loginUid, productId)));
        r.set("noavailableCoupons", null);
        return r;
    }

    @Before(Tx.class)
    public Record rechargeOrder(String loginUid, double integral) {
        String orderNumber = IdGen.getOrderIdByUUId();
        Kv cond2 = Kv.by("id", IdGen.uuid());
        cond2.set("user_id", loginUid);
        cond2.set("state", "-1");
        cond2.set("orderNumber", orderNumber);
        cond2.set("integral", integral);
        double money = integral / 100;
        Db.update(Db.getSqlPara("mediaShop.saveUserRechargeOrder", cond2));
        return new Record().set("orderNumber", orderNumber).set("money", money);
    }

}
